<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ProductController extends Controller
{
    /**
     * 显示商品列表页面
     * 支持按商品名称搜索
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = Product::query();

        // 搜索功能
        if ($request->has('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        // 获取分页数据
        $products = $query->paginate(10);

        return view('products.index', compact('products'));
    }

    /**
     * 显示创建商品的表单页面
     * 
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('products.create');
    }

    /**
     * 保存新创建的商品
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
        ]);

        $validated['stock'] = 0;
        $validated['sales_count'] = 0;
        // $validated['is_saleable'] = false;

        Product::create($validated);

        return redirect()->route('products.index')
            ->with('success', '商品创建成功！');
    }

    /**
     * 显示编辑商品的表单页面
     * 
     * @param  \App\Models\Product  $product
     * @return \Illuminate\View\View
     */
    public function edit(Product $product)
    {
        return view('products.edit', compact('product'));
    }

    /**
     * 更新指定商品的信息
     * 
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, Product $product)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string|max:1000',
        ]);

        $product->update($validated);

        // 处理图片上传
        if ($request->hasFile('image')) {
            $product->addMediaFromRequest('image')
                ->toMediaCollection('product-images');
        }

        return redirect()->route('products.index')
            ->with('success', '商品更新成功！');
    }

    /**
     * 切换商品上架/下架状态
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\RedirectResponse
     */
    public function toggleSale(Product $product)
    {
        Log::info('Request received', [
            'method' => request()->method(),
            'url' => request()->url(),
            'all' => request()->all()
        ]);

        try {
            // 切换状态
            $product->status = !$product->status;
            $saved = $product->save();

            Log::info('Toggle operation result', [
                'saved' => $saved,
                'new_status' => $product->status
            ]);

            return redirect()
                ->back()
                ->with('success', $product->status ? '商品已上架' : '商品已下架');
        } catch (\Exception $e) {
            Log::error('Toggle operation failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return redirect()
                ->back()
                ->with('error', '操作失败：' . $e->getMessage());
        }
    }
}